<template>
  <basic-container>
    <el-row :gutter="24" class="dict-info">
      <el-col :span="6" style="padding-right: 0px;">
        <el-card class="border-card" shadow="never">
          <div slot="header" class="clearfix">
            <h4 class="el-card__title">字典类别</h4>
            <el-button type="text"
                       icon="el-icon-plus" circle
                       size="mini"
                       @click="handleConfigAdd"
                       style="float: right;margin-left: 10px;">
            </el-button>
            <el-button type="text"
                       icon="el-icon-edit" circle
                       size="mini"
                       @click="handleConfigEdit"
                       v-if="editVisible"
                       style="float: right;">
            </el-button>
            <el-button type="text"
                       icon="el-icon-delete" circle
                       size="mini"
                       @click="handleConfigDel"
                       v-if="editVisible"
                       style="float: right;">
            </el-button>
          </div>
          <el-tree
                  node-key="id"
                  ref="tree"
                  default-expand-all
                  highlight-current
                  :expand-on-click-node="false"
                  empty-text=""
                  :data="treeData"
                  :props="treeProps"
                  @node-click="handleNodeClick"
                  style="min-height: 580px; overflow: auto">
          </el-tree>
        </el-card>
        <vDialog
                :title="dialogTitle"
                :option="dialogOption"
                width="60%">
          <avue-form ref="form" v-model="configForm" :option="configOption">
          </avue-form>
          <template v-slot:footer>
            <el-button size="small" @click="dialogOption.show = false">取 消</el-button>
            <el-button size="small" type="primary" @click="handleConfigSubmit">确 定</el-button>
          </template>
        </vDialog>
      </el-col>
      <el-col :span="18" style="padding-left: 0px;">
        <el-card class="border-card dict-list-card" shadow="never">
          <div slot="header">
            <h4 class="el-card__title">字典列表</h4>
            <el-button type="primary"
                       icon="el-icon-plus"
                       @click="handleAdd"
                       size="small"
                       :disabled="addDisabled"
                       style="margin-left: 20px;">新增
            </el-button>
            <div class="el-card__tool" @keyup.enter="querySearch">
              <el-input placeholder="请输入查询条件" size="mini" style="width:300px;" v-model="queryStream">
                <el-button slot="append" size="mini" icon="el-icon-search" @click="querySearch"></el-button>
              </el-input>
            </div>
          </div>
          <avue-crud ref="crud"
                     class="dict-list"
                     :option="option"
                     :data="data"
                     v-model="ruleForm"
                     :page="page"
                     @on-load="onLoad"
                     @row-save="rowSave"
                     @row-update="rowUpdate"
                     @current-change="currentChange"
                     @size-change="sizeChange"
                     style="min-height: 580px;">
            <template slot-scope="scope" slot="menu">
              <el-button type="text"
                         icon="el-icon-edit"
                         size="small"
                         @click.stop="rowEdit(scope.row, scope.index)">编辑
              </el-button>
              <el-button type="text"
                         icon="el-icon-delete"
                         size="small"
                         @click="rowDel(scope.row,scope.index)">删除
              </el-button>
            </template>
            <template slot-scope="{row}"
                      slot="configId">
              {{row.configName}}
            </template>
            <template slot-scope="{row}"
                      slot="parentId">
              {{row.parentName}}
            </template>
          </avue-crud>
        </el-card>
      </el-col>
    </el-row>
  </basic-container>
</template>
<script>
  import { configTree, getList, dictTree, verifyConfigUnique, addConfig, editConfig, updateConfig, removeConfig, verifyUnique, add, update, remove } from "@/api/system/dict";
  const DIC = {
    LEVEL: [{
      label: '国家标准字典',
      value: '0'
    }, {
      label: '地方标准字典',
      value: '1'
    }, {
      label: '行业标准字典',
      value: '2'
    }, {
      label: '自定义字典',
      value: '3'
    }]
  }
  export default {
    name: "dict-info",
    inheritAttrs: false,
    components: {
      vDialog: () => import('_c/vDialog'),
    },
    data() {
      const validConfigCode = (rule, value, callback) => {
        let data = {value: value};
        if (this.configForm.id) {
          data = {value: value, id: this.configForm.id};
        }
        verifyConfigUnique(data).then(data => {
          if (!data.success)
            callback(new Error('此类别编码已被使用!'))
          else
            callback()
        })
          .catch(err => {
            console.log(err)
            callback(new Error('验证失败!'))
          })
      };
      const validCode = (rule, value, callback) => {
        let data = {value: value, configId: this.ruleForm.configId};
        if (this.ruleForm.id) {
          data = {value: value, id: this.ruleForm.id, configId: this.ruleForm.configId};
        }
        verifyUnique(data).then(data => {
          if (!data.success)
            callback(new Error('此字典编码已被使用!'))
          else
            callback()
        })
          .catch(err => {
            console.log(err)
            callback(new Error('验证失败!'))
          })
      };
      return {
        editVisible: false,
        dialogOption:{
          show: false
        },
        dialogTitle: '',
        addDisabled: true,
        treeProps: {
          label: "title",
          value: 'id',
          children:'children'
        },
        treeData: [],
        queryStream: '',
        query: {},
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        option: {
          border: true,
          tree: true,
          addBtn: false,
          columnBtn: false,
          refreshBtn: false,
          searchBtn: false,
          editBtn: false,
          delBtn: false,
          index: true,
          defaultExpandAll:true,
          indexLabel: '序号',
          size: 'small',
          // dialogHeight: 300,
          menuWidth: 160,
          column: [
            {
              label: "字典类别",
              prop: "configId",
              type: "select",
              props: {
                value: 'id',
                label: "title"
              },
              // slot: true,
              hide: true,
              dicData: [],
              disabled: true,
              span: 24,
              rules: [
                {required: true, message: "请选择字典类别", trigger: "blur"}
              ]
            },
            {
              label: "字典键值",
              prop: "code",
              search: false,
              maxlength: 36,
              rules: [
                {required: true, message: '请输入字典键值', trigger: 'blur'},
                {min: 1, max: 16, message: '长度在 1 到 16 个字符'},
                {pattern: /^[A-Za-z0-9_]+$/, message: '只能输入英文、数字或下划线'},
                {validator: validCode, trigger: 'blur'}
              ]
            },
            {
              label: "字典名称",
              prop: "name",
              search: false,
              rules: [
                {required: true, message: '字典名称', trigger: 'blur'},
                {min: 1, max: 128, message: '长度在 2 到 128 个字符'}
              ]
            },
            {
              label: "上级字典",
              prop: "parentId",
              type: "tree",
              // hide: true,
              props: {
                value: 'id',
                label: "title"
              },
              slot: true,
              dicData: [],
              rules: [{
                required: false,
                message: "请选择上级字典",
                trigger: "click"
              }]
            },
            {
              label: "排序",
              prop: "sortOrder",
              type: 'number',
              span: 8,
              search: false,
              hide: true,
              value: 1,
              minRows: 1,
              maxRows: 999
            },
            {
              label: "字典说明",
              prop: "remark",
              type: "textarea",
              search: false,
              hide: true,
              minWidth: '200',
              span: 24,
              minRows: 3
            },
          ]
        },
        data: [],
        ruleForm: {},
        configOption: {
          mock: true,
          menuBtn: false,
          size: 'small',
          column: [
            {
              label: "类别编码",
              prop: "code",
              span: 12,
              maxlength: 36,
              rules: [
                {required: true, message: '请输入类别编码', trigger: 'blur'},
                {min: 3, max: 36, message: '长度在 3 到 36 个字符'},
                {pattern: /^[A-Za-z0-9_]+$/, message: '只能输入英文、数字或下划线'},
                {validator: validConfigCode, trigger: 'blur'}
              ]
            },
            {
              label: "类别名称",
              prop: "name",
              span: 12,
              rules: [
                {required: true, message: '请输入类别名称', trigger: 'blur'},
                {min: 2, max: 128, message: '长度在 2 到 128 个字符'}
              ]
            },
            {
              label: "字典级别",
              prop: "type",
              type: "select",
              dicData: DIC.LEVEL,
              mock: {
                type: 'dic',
              },
              rules: [
                {required: true, message: '请选择字典级别', trigger: 'blur'},
              ]
            },
            {
              label: "排序",
              prop: "sortOrder",
              type: 'number',
              span: 8,
              valueDefault: 1,
              minRows: 1,
              maxRows: 999
            },
          ]
        },
        configForm: {
          id: ''
        },
      }
    },
    created() {
      this.getConfigTree();
    },
    // watch: {
    //   'ruleForm.configId'() {
    //     if (this.ruleForm.configId !== '') {
    //       getDictTree(this.ruleForm.configId).then(res => {
    //         console.log(res.data)
    //         const index = this.$refs.crud.findColumnIndex("parentId");
    //         this.option.column[index].dicData = res.data;
    //       });
    //     }
    //   }
    // },
    methods: {
      getConfigTree() {
        this.treeData = [];
        configTree().then(res => {
          this.treeData = res.data;
        })
        this.dialogOption.show = false;
        this.editVisible = false;
        this.addDisabled = true;
      },
      onLoad(page, params = {}) {
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data;
          this.page.total = data.total;
          this.data = data.records;
        });
      },
      handleAdd() {
        const index = this.$refs.crud.findColumnIndex("configId");
        this.option.column[index].dicData = this.treeData;
        this.ruleForm={configId: this.query.configId}
        dictTree(this.query.configId).then(res => {
          const index = this.$refs.crud.findColumnIndex("parentId");
          this.option.column[index].dicData = res.data;
          this.option.column[index].disabled = false;
        });
        this.$refs.crud.rowAdd();
      },
      rowSave(row, loading, done) {
        add(row).then(ret => {
          if (ret.success) {
            loading();
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          } else {
            done();
            this.$message({
              type: "error",
              message: ret.msg
            });
          }
        }, error => {
          done();
          console.log(error);
        })
      },
      rowEdit(row, index) {
        const cindex = this.$refs.crud.findColumnIndex("configId");
        this.option.column[cindex].dicData = this.treeData;
        dictTree(row.configId).then(res => {
          const dindex = this.$refs.crud.findColumnIndex("parentId");
          this.option.column[dindex].dicData = res.data;
          this.option.column[dindex].disabled = true;
        });
        this.$refs.crud.rowEdit(row, index);
      },
      rowUpdate(row, index, loading, done) {
        update(row).then(ret => {
          if (ret.success) {
            loading();
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          } else {
            done();
            this.$message({
              type: "error",
              message: ret.msg
            });
          }
        }, error => {
          done();
          console.log(error);
        });
      },
      rowDel(row, index) {
        this.$confirm("确定要删除该字典项吗?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row);
          })
          .then(ret => {
            if (ret.success) {
              this.onLoad(this.page);
              this.$message({
                type: "success",
                message: "操作成功!"
              });
            } else {
              this.$message({
                type: "error",
                message: ret.msg
              });
            }
          }).catch(() => {
        });
      },
      handleConfigAdd() {
        this.dialogTitle = '新 增';
        this.dialogOption.show = true;
        this.initFormClean();
      },
      handleNodeClick(data) {
        this.queryStream = '';
        let configId = data.id;
        if (configId != '0' && configId != '1' && configId != '2' && configId != '3') {
          this.editVisible = true;
          this.query.configId = configId;
          this.addDisabled = false;
        } else {
          this.editVisible = false;
          this.query.configId = '';
          this.addDisabled = true;
        }
        this.query.query = "";
        this.page.currentPage = 1;
        this.onLoad(this.page, this.query);
      },
      handleConfigEdit() {
        if (this.query.configId) {
          editConfig(this.query.configId).then(ret => {
            if (ret.data) {
              this.dialogTitle = '编 辑';
              this.dialogOption.show = true;
              this.configForm = ret.data;
            } else {
              this.$message({
                type: "error",
                message: ret.msg
              });
            }
          }, error => {
            console.log(error);
          })
        }
      },
      handleConfigSubmit(){
        this.$refs.form.validate(vaild=>{
          if(vaild){
            if (this.configForm.id) {
              updateConfig(this.configForm).then(ret => {
                if (ret.success) {
                  this.getConfigTree();
                  this.$message({
                    type: "success",
                    message: "操作成功!"
                  });
                } else {
                  this.$message({
                    type: "error",
                    message: ret.msg
                  });
                }
              }, error => {
                console.log(error);
              })
            } else {
              addConfig(this.configForm).then(ret => {
                if (ret.success) {
                  this.getConfigTree();
                  this.$message({
                    type: "success",
                    message: "操作成功!"
                  });
                } else {
                  this.$message({
                    type: "error",
                    message: ret.msg
                  });
                }
              }, error => {
                console.log(error);
              })
            }
          }
        })
      },
      handleConfigDel() {
        if (this.query.configId) {
          this.$confirm("确定要删除该字典类别?", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
            .then(() => {
              return removeConfig(this.query.configId);
            })
            .then(ret => {
              if (ret.success) {
                this.getConfigTree();
                this.$message({
                  type: "success",
                  message: "操作成功!"
                });
              } else {
                this.$message({
                  type: "error",
                  message: ret.msg
                });
              }
            }).catch(() => {
          });
        }
      },
      //初始化对话框相关
      initFormClean() {
        this.configForm = {
          id: "",
          code: "",
          name: "",
          type: "",
          sortOrder: 1
        };
      },
      currentChange(currentPage) {
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize) {
        this.page.pageSize = pageSize;
      },
      querySearch() {
        this.query.query = this.queryStream;
        this.page.currentPage = 1;
        this.onLoad(this.page, this.query);
      }
    }
  }
</script>
<style scoped lang="scss">
  @import "~_s/placeholders";
  @import '~_s/table-list';
  ::v-deep .dict-list {
    @extend %fullsize;
    @extend %table-list;
    .avue-crud__menu {
      display: none;
    }
  }
  ::v-deep .dict-info {
    .el-card {
      .el-card__header {
        padding: 5px 15px;
      }
      .el-card__title {
        font-size: 14px;
      }
    }
  }
</style>